<template>
  <div id="userManagePage">
    <!-- 搜索表单 -->
    <a-form class="searchForm" layout="inline" :model="searchParams" @finish="doSearch">
      <a-row :wrap="false">
        <a-col flex="30%">
          <a-form-item flex="50" label="账号">
            <a-input v-model:value="searchParams.userAccount" placeholder="输入账号" allow-clear />
          </a-form-item>
        </a-col>
        <a-col flex="30%">
          <a-form-item flex="20" label="用户名">
            <a-input v-model:value="searchParams.userName" placeholder="输入用户名" allow-clear />
          </a-form-item>
        </a-col>
        <a-col flex="30%">
          <a-form-item flex="20" label="角色">
            <a-radio-group
              v-model:value="searchRole.role"
              :options="searchRoleList"
              @change="handleRoleChange"
            />
          </a-form-item>
        </a-col>
        <a-col flex="30%">
          <div flex="auto" id="right">
            <a-form-item>
              <a-button type="primary" html-type="submit">搜索用户</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" html-type="submit" @click="showAddModal">添加用户</a-button>
              <a-modal v-model:open="openAdd" title="添加用户" @ok="handleAdd()">
                <a-form :model="formStateRegister" name="basic" autocomplete="off">
                  <a-form-item
                    label="账号 : "
                    name="userAccount"
                    :rules="[{ required: true, message: '请输入账号' }]"
                  >
                    <a-input
                      v-model:value="formStateRegister.userAccount"
                      placeholder="请输入账号"
                    />
                  </a-form-item>
                  <a-form-item label="用户名 : " name="用户名">
                    <a-input v-model:value="formStateRegister.userName" />
                  </a-form-item>
                  <a-form-item label="用户头像" name="用户头像">
                    <a-input
                      v-model:value="formStateRegister.userAvatar"
                      placeholder="目前只支持URL方式上传头像"
                    />
                  </a-form-item>
                  <a-form-item label="自我介绍" name="自我介绍">
                    <a-textarea
                      v-model:value="formStateRegister.userProfile"
                      placeholder=""
                      :auto-size="{ minRows: 2, maxRows: 5 }"
                    />
                  </a-form-item>
                  <a-form-item>
                    <span>角色：</span>
                    <a-radio-group v-model:value="roleAdd" :options="roleList" />
                  </a-form-item>
                  <div class="tips">密码默认为: 12345678</div>
                  <div class="tips" style="height: 20px"></div>
                </a-form>
              </a-modal>
            </a-form-item>
          </div>
        </a-col>
      </a-row>
    </a-form>
    <div style="margin-bottom: 16px" />
    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'userAvatar'">
          <a-image :src="record.userAvatar" :width="120" />
        </template>
        <template v-else-if="column.dataIndex === 'userRole'">
          <div v-if="record.userRole === 'admin'">
            <a-tag color="green">{{ UserRole.admin }}</a-tag>
          </div>
          <div v-else>
            <a-tag color="blue">{{ UserRole.user }}</a-tag>
          </div>
        </template>
        <template v-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-button danger @click="doDelete(record.id)">删除</a-button>
          <a-button type="primary" @click="showModal(record.id)" style="margin-left: 10px"
            >编辑
          </a-button>
          <a-modal v-model:open="open" title="编辑用户信息" @ok="handlepdate()">
            <a-form
              name="basic"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 16 }"
              autocomplete="off"
            >
              <a-form-item label="用户名" name="用户名">
                <a-input v-model:value="formState.userName" />
              </a-form-item>
              <a-form-item label="用户头像" name="用户头像">
                <a-input
                  v-model:value="formState.userAvatar"
                  placeholder="目前只支持URL方式上传头像"
                />
              </a-form-item>
              <a-form-item label="自我介绍" name="自我介绍">
                <a-textarea
                  v-model:value="formState.userProfile"
                  placeholder=""
                  :auto-size="{ minRows: 2, maxRows: 5 }"
                />
              </a-form-item>
              <a-form-item>
                <a-radio-group v-model:value="role" :options="roleList" />
              </a-form-item>
            </a-form>
          </a-modal>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import {
  addUserUsingPost,
  deleteUserUsingPost,
  listUserVoByPageUsingPost,
  updateUserUsingPost,
} from '@/api/userController.ts'
import dayjs from 'dayjs'
import { getKeyByValue, UserRole } from '@/constant/UserRoleEnums.ts'

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
  },
  {
    title: '账号',
    dataIndex: 'userAccount',
  },
  {
    title: '用户名',
    dataIndex: 'userName',
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
  },
  {
    title: '简介',
    dataIndex: 'userProfile',
  },
  {
    title: '用户角色',
    dataIndex: 'userRole',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]

const doDelete = async (id: number) => {
  const res = await deleteUserUsingPost({ id })
  console.log('res', res)
  if (res.code === 0) {
    message.success('删除成功')
    // 刷新数据
    await fetchData()
  } else {
    message.error('删除失败')
  }
}

// 数据
const dataList = ref<API.UserVO[]>([])
const total = ref(0)

// 搜索条件
const searchParams = reactive<API.UserQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'ascend',
})

// 获取数据
const fetchData = async () => {
  const res = await listUserVoByPageUsingPost({
    ...searchParams,
  })
  if (res) {
    dataList.value = res.data.records ?? []
    total.value = res.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.message)
  }
}

// 表格变化之后，重新获取数据
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 搜索数据
const doSearch = () => {
  // 重置页码
  searchParams.current = 1
  fetchData()
}

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current,
    pageSize: searchParams.pageSize,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共 ${total} 条`,
  }
})

onMounted(() => {
  fetchData()
})

// 记录编辑用户的id
const editUserId = ref<number>()
const open = ref<boolean>(false)
// 点击编辑
const showModal = (id: number) => {
  editUserId.value = id
  open.value = true
}
const handlepdate = async () => {
  // console.log("角色",role.value,"用户名",formState.userName)
  formState.userRole = getKeyByValue(role.value) as string
  formState.id = editUserId.value

  const res = await updateUserUsingPost(formState)
  if (res?.code === 0) {
    message.success('更新成功')
  } else {
    message.error('更新失败')
  }
  fetchData()
  open.value = false
}

// 搜索角色
const searchRole = reactive({
  role: UserRole.all, // 初始化为“所有”
})

const searchRoleList = [UserRole.admin, UserRole.user, UserRole.all]

// 处理角色变更
const handleRoleChange = () => {
  if (searchRole.role == '所有') {
    searchParams.userRole = ''
    return
  }
  // console.log(searchRole.role)
  searchParams.userRole = getKeyByValue(searchRole.role) as string
}

// 编辑用户信息
const formState = reactive<API.UserUpdateRequest>({})
// 单选框
const roleList = [UserRole.admin, UserRole.user]
const role = ref<string>(UserRole.admin)

// 用于接受表单输入的值
const formStateRegister = reactive<API.UserAddRequest>({})

// 添加用户弹窗开关
const openAdd = ref<boolean>(false)
// 添加用户
const showAddModal = () => {
  openAdd.value = true
}

const roleAdd = ref<string>(UserRole.admin)
// 确认添加用户
const handleAdd = async () => {
  formStateRegister.userRole = getKeyByValue(roleAdd.value) as string
  const res = await addUserUsingPost(formStateRegister)
  if (res?.code === 0) {
    message.success('添加成功')
  } else {
    message.error('添加失败,' + res?.message)
  }
  fetchData()
}
</script>

<style scoped>
#userManagePage :deep(.searchForm) {
  width: 100% !important;
}

:deep(#right) {
  display: flex ;
  gap: 4px;
}
</style>
